package com.fenrirtec.aepp.portal.api;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.fenrirtec.aepp.common.dto.AuditFlowDto;
import com.fenrirtec.aepp.common.dto.MemberDto;
import com.fenrirtec.aepp.common.service.MemberManageService;
import com.fenrirtec.aepp.common.service.impl.MemberManageServiceImpl;
import com.fenrirtec.aepp.common.support.JSONActionSupport;
import com.fenrirtec.core.definition.BaseDefinition.API;
import com.fenrirtec.core.exception.DatabaseException;
import com.fenrirtec.core.exception.UnexpectedException;

public class SendPostAPI extends JSONActionSupport {

	private static final long serialVersionUID = 1L;

	private static final Logger logger = LoggerFactory.getLogger(SendPostAPI.class);

	public SendPostAPI() {
	}
	
	private String param;

	public String getParam() {
		return this.param;
	}

	public void setParam(String param) {
		this.param = param;
	}

	@Override
	protected List<ErrorInfo> doValidate() {
		return null;
	}

	@Override
	protected JSONObject doExecute() {
		MemberManageService memberService = new MemberManageServiceImpl();
		
		try {
			JSONObject jsonObj = JSONObject.parseObject(this.param);
			String memberLoginName = jsonObj.getString("member_login_name");
			String postNo = jsonObj.getString("post_no");
			MemberDto memberDto = memberService.memberInfo(memberLoginName);
			AuditFlowDto auditFlowDto = new AuditFlowDto();
			auditFlowDto.setMemberLoginName(memberDto.getMemberLoginName());
			auditFlowDto.setAuditSequence(memberDto.getLastestAuditSequence());
			auditFlowDto.setAuditPhase(memberDto.getLastestAuditPhase());
			if (memberDto.getLastestAuditResult().intValue() == 2) {
			    auditFlowDto.setAuditResult(1);
			} else {
			    auditFlowDto.setAuditResult(9);
			}
			auditFlowDto.setAuditComment(postNo);
			auditFlowDto.setLoginName(memberDto.getMemberLoginName());
			auditFlowDto.setUpdateUser(memberDto.getMemberLoginName());
			memberService.updateAuditResult(auditFlowDto);
			if (memberDto.getLastestAuditResult().intValue() != 2) {
			    auditFlowDto.setAuditSequence(memberDto.getLastestAuditSequence() + 1);
	            auditFlowDto.setAuditPhase(memberDto.getLastestAuditPhase() + 1);
	            auditFlowDto.setAuditResult(1);
	            memberService.insertAuditFlow(auditFlowDto);
			}
		} catch (DatabaseException e) {
			if (logger.isErrorEnabled()) {
				logger.error("database error occurred.", e);
			}
			throw new JSONActionStatusException(API.Common.Status.DB_ERROR, e);
		} catch (UnexpectedException e) {
			if (logger.isErrorEnabled()) {
				logger.error("unexpected error occurred.", e);
			}
			throw new JSONActionStatusException(API.Common.Status.DB_ERROR, e);
		}

		JSONObject root = new JSONObject();
		root.put(API.Common.Response.STATUS, API.Common.Status.SUCCESS);
		return root;
	}
}
